package org.exam.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.exam.system.domain.Menu;
import org.exam.system.mapper.MenuMapper;
import org.exam.system.query.MenuQuery;
import org.exam.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class       MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;


    @Override
    @Transactional
    public void add(Menu menu) {
        menuMapper.add(menu);
        //添加

    }

    @Override
    @Transactional
    public void delete(Long id) {
        menuMapper.delete(id);
        //条件删除
    }

    @Override
    public Menu get(Long id) {
        return menuMapper.get(id);
    }

    @Override
    public List<Menu> getAll() {
        return menuMapper.getAll();
    }

    @Override
    @Transactional
    public void update(Menu menu) {
        menuMapper.update(menu);
    }

    @Override
    public void patchDelete(Long[] ids) {
        menuMapper.patchDelete(ids);
    }

    @Override
    public PageInfo<Menu> queryPage(MenuQuery menuQuery) {
        PageHelper.startPage(menuQuery.getCurrentPage(), menuQuery.getPageSize());
        List<Menu> data = menuMapper.queryPage(menuQuery);
        return new PageInfo<>(data);
    }

    private List<Menu> getTypeTree() {
        List<Menu> typeTree = new ArrayList<>();
        List<Menu> types = menuMapper.getAll();
        Map<Long, Menu> map = new HashMap<>();
        for (Menu type : types) {
            map.put(type.getId(), type);
        }
        for (Menu type : types) {
            if (type.getParentId() == null) {
                typeTree.add(type);
            } else {
                Long parentId = type.getParentId();
                Menu parentType = map.get(parentId);
                if (parentId != null) {
                    List<Menu> children = parentType.getChildren();
                    children.add(type);
                }
            }
        }
        return typeTree;
    }

    @Override
    @Cacheable(cacheNames = "Menu", key = "'typeTree'")
    public List<Menu> typeTree() {
        return getTypeTree();
    }


}
